package com.example.controller;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.example.pojo.Aircraft;
import com.example.service.AircraftService;
import com.example.service.AreaService;
import com.example.utils.Page;
import com.example.utils.Result;
import io.swagger.annotations.Api;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.net.URLEncoder;


@CrossOrigin//允许跨域请求
@RestController//将类中的方法返回值都作为响应体返回
@RequestMapping("/wzz")
@Api(tags = "飞机管理")
public class AircraftController {
    @Autowired
    private AircraftService aircraftService;
    @Autowired
    private AreaService areaService;

    @GetMapping("/selectAllAircraft")
    public Result selectAllAircraft(@RequestParam(value = "originName",defaultValue = "")String originName,
                                    @RequestParam(value = "destinationName",defaultValue = "")String destinationName,
                                    @RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                    @RequestParam("pageSize")Integer pageSize){

        Page page = new Page<>(pageNum,pageSize, aircraftService.count(originName,destinationName));
        page.setList(aircraftService.selectAllAircraft(originName, destinationName,page.getStart(), pageSize));
        Map<String, Object> map = new HashMap<>();
        map.put("list", page.getList());
        map.put("count", page.getTotalCount());//总记录数
        map.put("pageSize", pageSize);//每页记录数
        map.put("pageNum", pageNum);//当前页码
        return new Result<>("200", "查询成功", map);
    }

    @PostMapping("/addAircraft")//添加飞机
    public Result addAircraft(@RequestBody Aircraft aircraft) {
        int count = aircraftService.addAircraft(aircraft);
        Map<String, Object> map = new HashMap<>();
        if (count > 0) {
            map.put("count", 200);
            map.put("data", aircraft);
            map.put("msg", "添加成功");
        } else {
            map.put("count", 444);
            map.put("data", null);
            map.put("msg", "添加失败");
        }
        return new Result<>("222", "调用成功", map);
    }

    @GetMapping("/deleteAircraft")//删除飞机
    public Result deleteAircraft(@RequestParam("id") Integer id) {
        int count = aircraftService.deleteAircraft(id);
        Map<String, Object> map = new HashMap<>();
        if (count > 0) {
            map.put("count", 200);
            map.put("data", null);
            map.put("msg", "删除成功");
        } else {
            map.put("count", 444);
            map.put("data", null);
            map.put("msg", "删除失败");
        }
        return new Result<>("222", "调用成功", map);
    }

    @PostMapping("/updateAircraft")//修改飞机
    public Result updateAircraft(@RequestBody Aircraft aircraft) {
        int count = aircraftService.updateAircraft(aircraft);
        Map<String, Object> map = new HashMap<>();
        if (count > 0) {
            map.put("count", 200);
            map.put("data", aircraft);
            map.put("msg", "更新成功");
        } else {
            map.put("count", 444);
            map.put("data", null);
            map.put("msg", "更新失败");
        }
        return new Result<>("222", "调用成功", map);
    }

    @GetMapping("/selectById")//根据id查询飞机
    public Result selectById(@RequestParam("id") Integer id) {
        Aircraft aircraft = aircraftService.selectById(id);
        Map<String,Object> map=new HashMap<>();
        if (aircraft != null) {
            map.put("code", 200);
            map.put("data", aircraft);
            map.put("msg", "查询成功");
        }else {
            map.put("code", 444);
            map.put("data", null);
            map.put("msg", "查询失败");
        }
        return new Result<>("222", "调用成功", map);
    }

    //导入excel

    @PostMapping("/uploadExcel")
    @Transactional
    public Result<String> uploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
        List<Aircraft> aircrafts = new ArrayList<>();//存储飞机数据
        Workbook workbook = new XSSFWorkbook(file.getInputStream());//获取工作簿
        Sheet sheet = workbook.getSheetAt(0);//获取第一个sheet
        DataFormatter formatter = new DataFormatter();//数据格式化
        for (Row row : sheet) {
            if (row.getRowNum() == 0) continue; // 跳过表头
            Aircraft aircraft = new Aircraft();

            aircraft.setOrigin(Integer.parseInt(formatter.formatCellValue(row.getCell(0))));//出发地
            aircraft.setDestination(Integer.parseInt(formatter.formatCellValue(row.getCell(1))));//目的地
            aircraft.setPrice(Double.parseDouble(formatter.formatCellValue(row.getCell(2))));//价格
//                QueryWrapper<Users> wrapper = new QueryWrapper<>();
//                wrapper.eq("employee_id",user.getEmployeeId());
//                Users users1 = usersService.getOne(wrapper);
//                if (users1!=null){
//                    throw new MyException("500","表中工号不是唯一，重复的工号为: " + user.getEmployeeId());
//                }

            aircraft.setFlight(formatter.formatCellValue(row.getCell(3)));//将数据添加到list中
            aircraft.setSeatLeft(Integer.parseInt(formatter.formatCellValue(row.getCell(4))));//将数据添加到list中0
            aircrafts.add(aircraft);//将数据添加到list中

        }

        aircraftService.addAircraft(aircrafts);
        return new Result("200", "文件上传并处理成功");
    }


    @GetMapping("/exportEasyExcel")
    public void exportEasyExcel(HttpServletResponse response, @RequestParam(value = "originName",defaultValue = "")String originName,
                                @RequestParam(value = "destinationName",defaultValue = "")String destinationName,
                                @RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                                @RequestParam( value = "pageSize",defaultValue = "999")Integer pageSize) throws IOException {
        try (var outputStream = response.getOutputStream()) {
            Page page = new Page<>(pageNum, pageSize, aircraftService.count(originName, destinationName));
            page.setList(aircraftService.selectAllAircraft(originName, destinationName, page.getStart(), pageSize));
            List<Aircraft> list = page.getList();
            // 动态构建表头
            List<List<String>> head = Arrays.asList(
                    Arrays.asList("出发地"),
                    Arrays.asList("目的地"),
                    Arrays.asList("价格"),
                    Arrays.asList("飞机编号"),
                    Arrays.asList("剩余座位")
            );

            // 转换数据为 List<List<Object>>
            List<List<Object>> exportData = new ArrayList<>();
            for (Aircraft aircraft : list) {
                List<Object> rowData = new ArrayList<>();
                String originCityName = areaService.selectCityNameById(aircraft.getOrigin());
                String destinationCityName = areaService.selectCityNameById(aircraft.getDestination());
                rowData.add(originCityName);
                rowData.add(destinationCityName);
                rowData.add(aircraft.getPrice());
                rowData.add(aircraft.getFlight());
                rowData.add(aircraft.getSeatLeft());
                exportData.add(rowData);
            }
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("机票记录表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 直接使用 exportData 进行导出
            EasyExcel.write(outputStream)
                    .head(head)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("飞机记录")
                    .doWrite(exportData);
        } catch (IOException e) {
            e.printStackTrace();
            // 记录异常信息
            System.err.println("导出 Excel 时出现 IO 异常：" + e.getMessage());
        }
    }



}
